package al.xc.common.middleware;

import al.xc.common.util.SelfThreadLocal;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;

@Slf4j
public class ContextHolder {

    public final static String USER_TOKEN = "USER_TOKEN";

    private static SelfThreadLocal<Map<String,Object>> threadLocal = new SelfThreadLocal<>(() -> new HashMap<>());

    /**
     * 不能实例化
     */
    private ContextHolder() {}

    /**
     * 获取数据
     * @param key
     * @param <T>
     * @return
     */
    public static <T> T get(String key) {
        if (null == key) {
            throw new IllegalArgumentException("key cannot be null");
        }
        Object result = threadLocal.get().get(key);
        return (T)result;
    }

    /**
     * 插入数据
     * @param key
     * @param vl
     * @param <T>
     */
    public static <T> void put(String key, T vl) {
        if (null == key) {
            throw new IllegalArgumentException("key cannot be null");
        }
        if (null == vl) {
            threadLocal.get().remove(key);
        } else {
            threadLocal.get().put(key, vl);
        }
    }

    /**
     * 移除
     * @param key
     */
    public static void remove(String key) {
        if (null == key) {
            throw new IllegalArgumentException("key cannot be null");
        }
        threadLocal.get().remove(key);
    }

    /**
     * 清空
     */
    public static void clear() {
        threadLocal.get().clear();
    }
}
